<template>
  <div>
    <t-dialog
      header="选择商品"
      :visible.sync="visible"
      width="60%"
      placement="center"
      :confirmOnEnter="true"
      :onClose="close"
    >
      <template #footer>
        <div class="footer-btn">
          <t-space size="22px">
            <div class="head-hint">
              <p>待选数量：</p>
              <p>{{ waitTotal }}</p>
            </div>
            <div class="head-hint">
              <p>已选数量：</p>
              <p>{{ selectTotal }}</p>
            </div>
          </t-space>
          <div>
            <t-button :theme="confirmBtn.theme" :loading="confirmBtn.loading" class="" @click="handleConfirm">
              {{ confirmBtn.content }}
            </t-button>
            <t-button theme="default" class="" @click="close">取消</t-button>
          </div>
        </div>
      </template>
      <div class="filter ">
        <t-space size="12px">
          <t-select style="width: 220px;" v-model="params.warehouse_id" :options="storeOptions" clearable
                    @change="getData" placeholder="全部">
            <template #label>
              <icon-font name="layers" style="color: #000;"/>
            </template>
          </t-select>

          <t-input style="width: 220px;" v-model="params.key" clearable @change="changeKey" @enter="getData"
                   placeholder="产品关键字搜索">
            <template #label>
              <icon-font name="search" size="16px" style="color:#000;font-weight: bold"/>
            </template>
          </t-input>
        </t-space>
      </div>
      <div class="mt16">
        <t-table
          rowKey="id"
          :data="lists"
          :columns="columns"
          :stripe="stripe"
          :bordered="bordered"
          :hover="hover"
          :size="size"
          :height="maxHeight"
          :table-layout="tableLayout ? 'auto' : 'fixed'"
          :showHeader="showHeader"
          cellEmptyContent="-"
          resizable
          :loading="loading"
          :pagination="pagination"
          :selected-row-keys="selectedRowKeys"
          @select-change="rehandleSelectChange"
        >
          <template #product_title="{row}">
            <p>{{ row.product_title }}</p>
            <p v-if="row.is_sn" class="" style="font-size: 12px;color: rgba(0,0,0,0.7);">SN:{{ row.sn }}</p>
          </template>
          <template #sell_price="{row}">
            <p>￥{{ row.sell_price }}</p>
          </template>
          <template #pay_price="{row}">
            <p>￥{{ row.pay_price }}</p>
          </template>
          <template #sell_product="{row}">
            <p>{{ row.sell_product }}</p>
          </template>
          <template #count="{row}">
            <t-input-number v-if="selectedRowKeys.includes(row.id)" v-model="row.count" theme="column"
                            :disabled="!!row.is_sn" :min="1" :max="row.is_sn ? 1 : row.quantity" @change="changeCount($event, row)"></t-input-number>
          </template>
        </t-table>
      </div>
    </t-dialog>
  </div>
</template>

<script>
import {IconFont} from "tdesign-icons-vue";
import {warehouse_product_stockListApi} from "@/api/warehouseInventory";
import {warehouseListApi} from "@/api/warehouse";

export default {
  name: 'SelectProduct',
  components: {IconFont},
  data() {
    return {
      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        {colKey: 'row-select', type: 'multiple',
          checkProps: this.selectCheckProps,
          width: 50, },
        {colKey: 'id', title: 'ID', width: 50, },
        {colKey: 'product_title', title: '产品信息', width: 180, fixed: 'left', ellipsis: true},
        {colKey: 'warehouse_name', title: '所属仓库', width: 150},
        {colKey: 'quantity', title: '库存', width: 80},
        {colKey: 'count', title: '选择数量', width: 140},
      ],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
      },
      selectedRowKeys: [],
      maxHeight: '50vh',
      loading: false,

      visible: false,

      storeOptions: [], // 仓库列表

      confirmBtn: {
        content: '确定',
        theme: 'primary',
        loading: false
      },
      params: {
        limit: 10, // integer 页数 必需 示例值:  10
        page: 1, // integer 页码 必需 示例值:  1
        warehouse_type: 0, // integer 可选 仓库类型：0平台；1代理商
        warehouse_id: '', // integer 仓库ID 可选
        product_id: '', // integer 产品ID 可选
        product_classify_id: '', // integer 产品分类ID 可选
        key: '', // string 搜索：产品名称 可选
        is_del: '', // integer 可选 删除（1回收站；0正常）
      },
      waitTotal: 0,
      selectTotal: 0,

      product: {}
    }
  },
  methods: {
    changeCount(value, row) {
      if (value > row.quantity) {
        this.$nextTick(()=> {
          const lists = this.lists.filter(item=> this.selectedRowKeys.includes(item.id)).filter(item=> item.id !== row.id)
          if (lists.length === 0) {
            if (row.quantity > this.product.quantity) {
              row.count = this.product.quantity
            } else {
              row.count = row.quantity
            }
          } else {
            const total = lists.reduce((total, item)=> total + item.count, 0)
            const waitTotal = this.product.quantity - total
            row.count = row.quantity > waitTotal ? waitTotal : row.quantity
          }
        })
        this.$message.warning('超出库存')
      }
    },
    selectCheckProps({row, rowIndex}) {
      return {disabled: (!row.quantity || this.waitTotal <= 0) && !this.selectedRowKeys.includes(row.id)}
    },
    handleConfirm() {
      if (this.waitTotal > 0) {
        this.$message.warning('未选够待选数量')
      } else {
        const lists = this.lists.filter(item=> this.selectedRowKeys.includes(item.id))
        this.$emit('select', {
          type: this.product.type,
          p_product_id: this.product.p_product_id,
          product_id: this.product.product_id,
          lists: lists,
          total: this.selectTotal
        })
        this.visible = false
      }
    },
    rehandleSelectChange(value, {currentRowData, currentRowKey, selectedRowData}) {
      if (currentRowKey === 'CHECK_ALL_BOX') {
        if (value.length) {
          for (let i = 0; i < selectedRowData.length; i++) {
            const currentRowKey = selectedRowData[i].id
            if (this.waitTotal > 0) {
              this.changeSelectData(value, currentRowKey)
            }
          }
        } else {
          for (let i = 0; i < this.selectedRowKeys.length; i++) {
            const currentRowKey = this.selectedRowKeys[i]
            this.changeSelectData([], currentRowKey)
          }
        }
      } else {
        this.changeSelectData(value, currentRowKey)
      }

      this.selectedRowKeys = value;

      const lists = this.lists.filter(item=> item.count <= 0)
      for (let i = 0; i < lists.length; i++) {
        if (this.selectedRowKeys.includes(lists[i].id)) {
          this.selectedRowKeys = this.selectedRowKeys.filter(item=> item !== lists[i].id)
        }
      }
    },
    changeSelectData(value, currentRowKey) {
      const index = this.lists.findIndex(item => item.id === currentRowKey)
      if (index !== -1) {
        if (value.includes(currentRowKey)) {
          if (this.lists[index].is_sn) {
            this.lists[index].count = 1
            this.waitTotal = this.waitTotal - this.lists[index].count
            this.selectTotal = this.selectTotal + this.lists[index].count
          } else {
            this.lists[index].count = this.lists[index].quantity > this.waitTotal ? this.waitTotal : this.lists[index].quantity
            this.waitTotal = this.waitTotal - this.lists[index].count
            this.selectTotal = this.selectTotal + this.lists[index].count
          }
        } else {
          this.waitTotal = this.waitTotal + this.lists[index].count
          this.selectTotal = this.selectTotal - this.lists[index].count
          this.lists[index].count = 0
        }
      }
    },
    changeKey() {
      clearTimeout(this.timer)
      this.timer = setTimeout(()=> {
        this.getData()
      }, 500)
    },
    getData() {
      this.pagination.defaultCurrent = 1
      this.getProductList()
    },
    // 获取产品列表
    getProductList() {
      this.loading = true
      this.params.page = this.pagination.defaultCurrent
      warehouse_product_stockListApi(this.params).then(res => {
        const selectList = this.product.selectList
        // 不是搜索时，初始化选择数量
        if (!(this.params.warehouse_id || this.params.key)) {
          this.waitTotal = this.product.quantity
          this.selectTotal = 0
        }

        this.lists = res.data.map(item=> {
          let count = 0;
          // 不是搜索时，初始化选择数量
          if (!(this.params.warehouse_id || this.params.key)) {
            if (this.selectedRowKeys && this.selectedRowKeys.length) {
              for (let i = 0; i < selectList.length; i++) {
                if (item.id === selectList[i].id) {
                  this.waitTotal = this.waitTotal - selectList[i].count
                  this.selectTotal = this.selectTotal + selectList[i].count
                }
              }
            }
          }
          if (selectList && selectList.length) {
            for (let i = 0; i < selectList.length; i++) {
              if (item.id === selectList[i].id) {
                count = selectList[i].count
                break
              }
            }
          }
          return {...item, count: count}
        })
        this.pagination.total = res.count
      }).catch(err => {
        console.log('err', err)
      }).finally(()=> {
        this.loading = false
      })
    },
    // 获取仓库列表
    getStoreList() {
      const params = {
        limit: 9999,
        page: 1,
        w_type: 0,
        key: '',
        status: 1
      }
      warehouseListApi(params).then(res=> {
        this.storeOptions = res.data.map(item=> ({label: item.name, value: item.id}))
      }).catch(err=> {
        console.log('err', err)
      })
    },
    open(row) {
      this.product = row
      this.waitTotal = row.quantity
      this.selectTotal = 0
      this.lists = [],
      this.selectedRowKeys = row.selectList ? row.selectList.map(item=> item.id) :[]
      this.params = {
        limit: 10, // integer 页数 必需 示例值:  10
        page: 1, // integer 页码 必需 示例值:  1
        warehouse_type: 0, // integer 可选 仓库类型：0平台；1代理商
        warehouse_id: '', // integer 仓库ID 可选
        product_id: row.product_id, // integer 产品ID 可选
        product_classify_id: '', // integer 产品分类ID 可选
        key: '', // string 搜索：产品名称 可选
        is_del: '', // integer 可选 删除（1回收站；0正常）
      }
      // 获取产品数据
      this.getData()
      // 获取仓库列表
      this.getStoreList()
      this.visible = true
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>

.footer-btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
  width: 100%;
  background-color: #F9F9F9;
  border-bottom: 1px solid #F9F9F9;
  border-radius: 0 0 var(--td-radius-medium) var(--td-radius-medium);
  padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xxl);

  display: flex;
  align-items: center;
  justify-content: space-between;


  .head-hint {
    display: flex;
    align-items: center;

    font-size: 16px;
    font-weight: 400;
    line-height: 19.6px;
    text-align: left;

    p:first-child {
      color: var(--td-font-gray-2);
    }
  }

}

</style>
